package 面向对象.TestEight;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author IT_Jay
 * @date 2021/11/25 23:06
 */

public class Frame4 {
    public JTextArea area1, area2;

    public static void main(String[] args) {
        Frame4 frame4 = new Frame4();
        frame4.init();
    }

    public void init() {
        JFrame frame = new JFrame("计算数值");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setLayout(null);
        area1 = new JTextArea(12, 14);
        area1.setBounds(25, 30, 200, 200);
        frame.add(area1);

        area2 = new JTextArea(12, 14);
        area2.setEditable(false);
        area2.setBounds(250, 30, 200, 200);
        frame.add(area2);
        addListener();
        frame.setVisible(true);
    }

    public void addListener() {
        area1.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 10) calc();
            }
        });
    }

    private void calc() {
        String content = area1.getText();
        String area_content = "";
        String[] strings;
        int sum = 0, avg;
        strings = content.split(",");
        for (int i = 0; i < strings.length; i++) {
            try {
                strings[i] = strings[i].trim();
                if (strings[i].endsWith("\n"))
                    strings[i].replace("\n","");
                int num = Integer.parseInt(strings[i]);
                sum += num;
            } catch (NumberFormatException e) {
                area_content = "数据输入有误";
                area2.setText(area_content);
                return;
            }
        }
        avg = sum / strings.length;
        area_content = "这组数据的总和为：" + sum + "\n 这组数据的平局值为：" + avg;
        area2.setText(area_content);
    }
}
